package org.mijia.dotsbox.utils;

import java.util.regex.Pattern;

public class StringUtils {
	private static final int SNIPPET_MAX = 200;
	
	public static String getSnippets(String str, String keyword) {
		String strContent = str.toLowerCase();
		String lowkey = keyword.toLowerCase();
		String snippet = "";
		int index = strContent.indexOf(lowkey);
		if(index != -1) {
			String leftString = str.substring(0, index);
			String rightString = str.substring(index);
			
			StringBuffer sb = new StringBuffer();
			if(leftString.length() < SNIPPET_MAX / 3)
				sb.append(leftString);
			else
				sb.append("... " + leftString.substring(leftString.length() - SNIPPET_MAX / 3));
			
			if(rightString.length() < SNIPPET_MAX * 2 / 3)
				sb.append(rightString);
			else
				sb.append(rightString.substring(0, SNIPPET_MAX * 2 / 3) + " ...");
			
			snippet = sb.toString();
		} else {
			if(str.length() < SNIPPET_MAX)
				snippet = str;
			else
				snippet = str.substring(0, SNIPPET_MAX) + "... ...";
		}
		return snippet;
	}
	
	public static String stripSpecialTags(String str) {
		if(str == null)
			return null;
		
		if(str.indexOf("&") != -1 && str.indexOf(";") != -1) {
			String regex = "&[^&;]+;";
			Pattern pattern = Pattern.compile(regex);
			str = pattern.matcher(str).replaceAll("");
		}
		return str;
	}
	
	public static String decorateToken(String str, String searchS, String prefix, String postfix) {
		String strContent = str.toLowerCase();
		String search = searchS.toLowerCase();
		int start = 0;
		int pos;
		StringBuffer result = new StringBuffer(strContent.length());
		while ((pos = strContent.indexOf(search, start)) >= 0) {
			result.append(str.substring(start, pos));
			result.append(prefix);
			result.append(str.subSequence(pos, search.length() + pos));
			result.append(postfix);
			start = pos + search.length();
		}
		result.append(str.substring(start));

		return result.toString();		
	}
	
	public static String replaceAll(String str, String searchS, String replace) {
		String strContent = str.toLowerCase();
		String search = searchS.toLowerCase();
		int start = 0;
		int pos;
		StringBuffer result = new StringBuffer(strContent.length());
		while ((pos = strContent.indexOf(search, start)) >= 0) {
			result.append(str.substring(start, pos));
			result.append(replace);
			start = pos + search.length();
		}
		result.append(str.substring(start));

		return result.toString();
	}

	public static String stripTags(String str) {

		/** First Check if String contains any Tags at all */
		if (str == null || str.indexOf('<') == -1 || str.indexOf('>') == -1)
			return str;

		str = RegexUtils.HTML_TAG_REGEX_PATTERN.matcher(str).replaceAll("");
		return str;
	}
}
